"""
velocityofreading.py

For Google App Engine

Created by Tristan on 2008-01-09.
Copyright (c) 2008 __MyCompanyName__. All rights reserved.
"""


# TODO
# Browser testing - IE, Safari, Firefox, Camino
# Check Google analytics
# Add favicon?


import cgi
import os
import logging

from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

import bkkeepr

amazonAPIKey = "1S64ZQMTY5GKZH4RMF82"

class MainPage(webapp.RequestHandler):
	def get(self):
		template_values = {
		}
		path = os.path.join(os.path.dirname(__file__), 'index.html')
		self.response.out.write(template.render(path, template_values))	

class ErrorHandler(webapp.RequestHandler):
	def get(self, pathgiven):
		self.error(500)
		template_values = {
		}
		path = os.path.join(os.path.dirname(__file__), '404.html')
		self.response.out.write(template.render(path, template_values))	

class UserHandler(webapp.RequestHandler):
	global amazonAPIKey
	def get(self, username):
		try:
			if len(username) == 0:
				self.error(404)
				path = os.path.join(os.path.dirname(__file__), '404.html')
				self.response.out.write(template.render(path, 0))					
				logging.error("Error: No username given")			
			else:
				readinggraph_error = 0
				cumulativegraph_error = 0
				b = bkkeepr.Bkkeepr(username, amazonAPIKey)
				#b.usecache = 1
				if b.getBookData():
					stats = b.getStatistics()
					readinggraph = b.getReadingGraph(600,200)
					if readinggraph == "There was a problem generating the graph, sorry.":
						readinggraph_error = 1
						logging.error("Error: There was a problem generating the reading graph for %s" % username)							
					cumulativegraph = b.getCumulativeReadingGraph(600,200)
					if cumulativegraph == "There was a problem generating the graph, sorry.":
						cumulativegraph_error = 1
						logging.error("Error: There was a problem generating the cumulative graph for %s" % username)							
				else:
					stats = "You haven't read enough books for us to calculate any statistics, sorry."
					readinggraph = ""
					cumulativegraph = ""
				books = b.booklist
				template_values = {
	     			'username' : username,
					'stats' : stats,
					'readinggraph' : readinggraph,
					'readinggraph_error' : readinggraph_error,
					'cumulativegraph' : cumulativegraph,
					'cumulativegraph_error' : cumulativegraph_error,
					'books' : books
				}
				path = os.path.join(os.path.dirname(__file__), 'user.html')
				self.response.out.write(template.render(path, template_values))	
		except Exception, message:
			# Clear output and return an error code.
			self.error(500)
			path = os.path.join(os.path.dirname(__file__), '500.html')
			self.response.out.write(template.render(path, 0))	
			logging.error("Exception: %s" % message)
		


application = webapp.WSGIApplication(
		                             [('/', MainPage),
		                              ((r'/users/(.*)', UserHandler)),
									  ((r'/(.*)', ErrorHandler))
									 ],
		                             debug=True)
def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()